import math
from openpyxl import Workbook
#剩余牌计算3.0

def calculate_probability(total_cards, target_cards, draw_num):
    """计算至少抽到一张目标牌的概率"""
    # 异常值处理
    if draw_num <= 0 or target_cards < 0 or total_cards <= 0:
        return 0.0
    if target_cards > total_cards or draw_num > total_cards:
        return 0.0

    # 当非目标牌不足时概率100%
    non_target = total_cards - target_cards
    if non_target < draw_num:
        return 1.0

    # 组合数计算
    try:
        fail_comb = math.comb(non_target, draw_num)
        total_comb = math.comb(total_cards, draw_num)
    except ValueError:
        return 0.0

    return 1 - (fail_comb / total_comb)


def get_valid_input(prompt, min_val=1):
    """获取有效正整数输入"""
    while True:
        try:
            value = int(input(prompt))
            if value >= min_val:
                return value
            print(f"输入值必须 ≥ {min_val}")
        except ValueError:
            print("请输入有效整数")


# 用户输入抽牌数
draw_num = get_valid_input("请输入要抽取的牌数：")

# 创建Excel文件
wb = Workbook()
ws = wb.active
ws.append(["剩余牌数", "目标牌数1", "目标牌数2", "目标牌数3", "目标牌数4"])

# 生成概率矩阵
for total in range(1, 27):
    row = [total]
    for target in [1, 2, 3, 4]:
        prob = calculate_probability(total, target, draw_num)
        row.append(f"{prob:.4%}")  # 格式化为百分比
    ws.append(row)

wb.save(f"E:/PYTHON花札牌计算/花札抽牌概率_{draw_num}张.xlsx")
print(f"\n生成完成！结果已保存至：抽牌概率_{draw_num}张.xlsx")
